package sim.states;

import ctf.model.Side;
import ctf.network.ProtocolError;
import sim.ISimulator;
import sim.ISimulator.State;
import utils.CTFGrammar;
/**
 * State responsible for the assignment of team sides.
 * @author N. Bhatia, A. Butt, N. Evans, C. Levesque, P. OKeefe
 *
 */
public class RequestSideState extends AbstractState {

	private boolean playerConnected = false;
	private Side otherTeamSide;

	public RequestSideState(ISimulator simulator) {
		super(simulator);
	}

	@Override
	public void request(int clientId, String request) throws ProtocolError {
		String[] splitString = request.split(" ");
		if (splitString.length == 2 && splitString[0].equals(CTFGrammar.REQUEST_SIDE)
				&& checkSide(splitString[1])) {
			this.simulator.setState(clientId, State.NEW_ROUND);
			if (this.playerConnected) {
				this.simulator.setTeamSide(clientId, otherTeamSide);
				if (otherTeamSide == Side.LEFT) {
					this.simulator.respond(clientId, CTFGrammar.ONSIDE + 0);

				} else {
					this.simulator.respond(clientId, CTFGrammar.ONSIDE + 1);
				}
			} else {
				this.playerConnected = true;
				if (Integer.parseInt(splitString[1]) == 1) {
					this.simulator.setTeamSide(clientId, Side.RIGHT);
					this.otherTeamSide = Side.LEFT;
					this.simulator.respond(clientId,CTFGrammar.ONSIDE + 1);
				} else if (Integer.parseInt(splitString[1]) == 0) {
					this.simulator.setTeamSide(clientId, Side.LEFT);
					this.otherTeamSide = Side.RIGHT;
					this.simulator.respond(clientId, CTFGrammar.ONSIDE + 0);
				} else {
					throw new ProtocolError(CTFGrammar.REQUEST_SIDE + " <0|1>", request);
				}
			}
		} else {
			throw new ProtocolError(CTFGrammar.REQUEST_SIDE + " <0|1>", request);
		}

	}

	private boolean checkSide(String string) {
		int side = Integer.parseInt(string);
		if (side == 0 || side == 1) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * Resets the state to reset.
	 */
	public void reset() {
		this.playerConnected = false;
	}

}
